import FileSaver from 'file-saver'
import XLSX from 'xlsx'


/**
 * 在cookie字符串中获取指定name的值
 * @param {String} key （name名）
 * @param {String} cookieStr （cookie字符串，格式类似 a=1;b=2）
 */

export function getCookieValue(key, cookieStr) {
	let str = cookieStr;
	if (str === null || str === '' || str === undefined) {
		str = '=';
	}
	var cookies = JSON.parse('{"' + str.replace(/=/g, '":"').replace(/;\s+/g, '","') + '"}');
	return cookies[key];
}

/**
 * 平滑移动到某个元素，如果是个class则为第一个元素。
 */

export function scroll(ele) {
	const scrollPart = document.querySelector(ele); // 目标节点的id或class
	const top = scrollPart.getBoundingClientRect().top;
	const pageY = window.pageYOffset;
	const endPosition = top + pageY;

	const startTime = +new Date();
	const duration = 500; //ms

	function run() {
		const time = +new Date() - startTime;

		window.scrollTo(0, pageY + top * (time / duration));
		run.timer = requestAnimationFrame(run);

		if (time >= duration) {
			window.scrollTo(0, endPosition);
			cancelAnimationFrame(run.timer);
		}
	}
	requestAnimationFrame(run);
}

/**
 * 表格导出为excel文件（可以配合element ui的tabel组件）
 * @param {Object} name 导出的文件名
 * @param {Object} type 导出的文件格式，一般为xlsx或csv
 */
export function exportExcel(vm, name, type, tb_id) {
	//表格项如果设置fixed属性会导致excel文件的数据重复，所以先得去掉再导出，导出完重置回原来的样子。
	vm.isFixed = false;
	vm.$nextTick(function() {
		//主要逻辑
		let wb = XLSX.utils.table_to_book(document.querySelector(tb_id));
		let wbout = XLSX.write(wb, {
			bookType: type,
			bookSST: true,
			type: 'array'
		})
		try {
			FileSaver.saveAs(new Blob([wbout], {
				type: 'application/octet-stream'
			}), name + '.' + type)
		} catch (e) {
			if (typeof console !== 'undefined') console.log(e, wbout)
		}
		vm.isFixed = 'right';
	})
}

function getProcessingTime(val, id) {
	let statusArr = val.statuss;
	let createDay = "";
	for (const i in statusArr) {
		if (statusArr[i].id == id) {
			createDay = statusArr[i].pivot.created_at;
		}
	}
	//获取接单的时间戳
	createDay = createDay.replace(/-/g, "/");
	var createTime = new Date(createDay).getTime();
	//获取当前的时间戳
	var nowTime = new Date().getTime();
	//获取处理时间戳
	let cha = nowTime - createTime;
	//转换天数
	let day = Math.floor(cha / 1000 / 60 / 60 / 24);
	let processingTime = day + "天";
	if (day <= 0) {
		//不够一天显示小时
		let hour = Math.floor((cha / 1000 / 60 / 60) % 24);
		processingTime = hour + "小时";
	}
	return processingTime;
}

//订单创建时间
function getOrderCreateTime(val) {
	let statusArr = val.statuss;
	let createDay = "";
	for (const i in statusArr) {
		if (statusArr[i].id == 1) {
			createDay = statusArr[i].pivot.created_at;
		}
	}
	return createDay;
}

//更新时间，做过倒序，直接拿第一条
function getUpdateTime(val) {
	let statusArr = val.statuss;
	let createDay = statusArr[0].pivot.created_at;
	return createDay;
}

//计算时间差
export function intervalTime(startTime, endTime,onlyDay) {
	var date1 = new Date(startTime); //开始时间
	var date2 = new Date(endTime); //结束时间
	var date3 = date2.getTime() - date1.getTime(); //时间差的毫秒数
	//计算出相差天数
	var days = Math.floor(date3 / (24 * 3600 * 1000));
	//计算出小时数

	var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));

	//计算相差秒数

	var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	// return days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒";
	return onlyDay?(days + "天 "):(days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒");
}

// 答复耗时
export function getTimeConsuming(value) {
		let createTime = ''
		if (value.statuss) {
			let sta = value.statuss
			if(sta[sta.findIndex(v => v.id == 20)]) {
				createTime = sta[sta.findIndex(v => v.id == 20)].pivot.created_at
			} else {
				createTime = value.updated_at
			}
		} else {
			createTime = value.updated_at
		}

		createTime = createTime.replace(/-/g, "/")
    createTime = new Date(createTime);
    //获取当前的时间戳
		var nowTime = ''
		if (value.status === '已补正' || value.status === '已答复') {
			let sta = value.statuss
			let timeDate= ''
			if(sta[sta.findIndex(v => v.id == 21)]) {
				timeDate = sta[sta.findIndex(v => v.id == 21)].pivot.created_at
			} else {
				return ''
			}
			nowTime = new Date(timeDate)
		} else {
			nowTime = new Date();
		}

    // let processingTime = ''
		//获取处理时间戳
		if ((nowTime - createTime) < 0) {
			return ''
		}
		let cha = nowTime - createTime

    // var month = day * 30
    // let year = month * 12


		let round2 = (cha / 1000 / 60 / 60 / 24).toFixed(2)
		let	processingTime = (Math.ceil(round2 * 10) / 10).toFixed(1)
		if (processingTime < 0) {
			return '0.0'
		}  else if (processingTime < 0.1) {
			return '0.1'
		} else {
			return processingTime;
		}

}

export const validateName = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输发明人姓名'));
	} else if (!(/^(([\u4e00-\u9fa5]|[a-zA-Z])+(，)?){0,}([\u4e00-\u9fa5]|[a-zA-Z])$/.test(value))) {
		callback(new Error('发明人姓名必须是中文。如果多个则必须用中文逗号"，" 隔开'));
	} else {
		callback();
	}
}

export const validateNull = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输入姓名'));
	} else {
		callback();
	}
}

export const validateOrganization = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输入所属单位'));
	} else {
		callback();
	}
}

export const validateEmail = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输入联系人邮箱'));
	} else if (!(/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/.test(value))) {
		callback(new Error('请输正确的邮箱'));
	} else {
		callback();
	}
}

export const validatePhone = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输入联系人电话'));
	} else if (!(/^1[3456789]\d{9}$/.test(value))) {
		callback(new Error('请输正确的电话号码'));
	} else {
		callback();
	}
}


export const validateId = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输入身份证号'));
	} else if (!(/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(value))) {
		callback(new Error('请输入正确的身份证号'));
	} else {
		callback();
	}
}

export const validateBank = (rule, value, callback) => {
	if (value != '') {
		if (!(/^[0-9]{16,19}$/.test(value))) {
			callback(new Error("请输入正确的银行卡号"));
		} else {
			callback()
		}
	} else {
		callback()
	}
}

export const validateAlipayNum = (rule, value, callback) => {
	if (value != '' && value) {
		if (/^1[3456789]\d{9}$/.test(value) || /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/.test(value)) {
			callback()
		} else {
			callback(new Error("请输入正确的支付宝账号"));
		}
	} else {
		callback()
	}
}


/**
 *
 * @param {Object} data  案件数据
 * @param {String} type 留言类型 1，给用户留言。 2，给流程留言
 */

export function agentLeaveWord (data, type, that) {
	let url = ''
	let id = data.id
	let params = {}

	that.$prompt('<p class="tl">请输入你的留言</p>', '留言', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		cancelButtonClass: 'el-button--warning',
		inputType: 'textarea',
		dangerouslyUseHTMLString: true,
		inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
		inputErrorMessage: '请输入留言内容。'
	}).then(({ value }) => {
		params = {
			order: id,
			message:value,
			type: 2
		}
		if (type == 1) {
			url = `api/consumer/${id}/send/message`
			that.$axios.post(url, params).then( res => {
				if (res.data.code == 200) {
					let receive_uid = data.consumer_id
					sendPrivateLetter(that, id, value, receive_uid, 'order')
				} else {
					that.$message.error(res.data.message)
				}
			})
		} else if (type == 2) {
			url = `api/consumer/${id}/process/message`
			that.$axios.post(url, params).then( res => {
				if (res.data.code == 200) {
					let receive_uid = data.process.id
					sendPrivateLetter(that, id, value, receive_uid, 'order')
				} else {
					that.$message.error(res.data.message)
				}
			})
		}
	}).catch(() => {
	})
}

/**
 *
 * @param {Object} that  实例对象
 * @param {String} id  案件id
 * @param {String} news 消息内容
 * @param {String} receive_uid 接受人id
 * @param {String} type 区分国知局前订单 还是国知局后订单 order 国知局前 finals 国知局后
 * @param {String} remarks 备注
 */
export function sendPrivateLetter (that, id, news, receive_uid, type, remarks ) {
	let params = {
		news: news,
		receive_uid: receive_uid
	}
	if (type == 'order') {
		params.order_id = id
	} else if (type == 'final') {
		params.finals_id = id
	}
	if (remarks) {
		params.remarks = remarks
	}
	that.$axios.post('api/news/add_private_letter', params).then (res => {
		if (res.data.code == 200) {
			that.$message({
				type: 'success',
				message: '发送私信成功'
			})
		} else {
			that.$message.error(res.data.error)
		}
	})
}
